// pages/page1/page1.js
Page({
  data: {
    goods: [],  // 从后端获取
    cart: { userId: 'cxr', items: [], total: 0 },
    dialogStatus: false,
  },

  onLoad() {
    this.fetchGoods();
  },

  // 从后端获取商品数据
  fetchGoods() {
    wx.request({
      url: 'http://localhost:8080/api/goods', 
      method: 'GET',
      success: (res) => {
        let goods = res.data.map((item, index) => ({
          ...item,
          show_status: index === 0 ? 'block' : 'none' // 默认展示第一个分类
        }));
        this.setData({ goods });
      },
      fail: (err) => {
        wx.showToast({ title: '加载商品失败', icon: 'none' });
        console.error("获取商品失败:", err);
      }
    });
  },

  // 获取商品对象
  getGoodsById(g_id) {
    g_id = Number(g_id);
    for (let category of this.data.goods) {
      for (let item of category.infos) {
        if (item.g_id === g_id) return item;
      }
    }
    return null;
  },

  // 切换右侧商品
  switchRightItems(e) {
    let index = e.currentTarget.dataset.index;
    let goods = this.data.goods;
    goods.forEach(i => i.show_status = 'none');
    goods[index].show_status = 'block';
    this.setData({ goods });
  },

  // 购物车操作（保持原逻辑）
  carOper(e) {
    let g_id = e.currentTarget.dataset.id;
    let oper = e.currentTarget.dataset.oper; 
    let cart = this.data.cart;
    let goodsItem = this.getGoodsById(g_id);
    if (!goodsItem) return;

    let exist = cart.items.find(i => i.g_id === g_id);

    if (oper === 'add') {
      if (exist) {
        exist.count++;
        exist.sum = exist.count * exist.g_price;
      } else {
        cart.items.push({ ...goodsItem, count: 1, sum: goodsItem.g_price });
      }
    } else if (oper === 'sub') {
      if (exist) {
        exist.count--;
        if (exist.count <= 0) {
          cart.items = cart.items.filter(i => i.g_id !== g_id);
        } else {
          exist.sum = exist.count * exist.g_price;
        }
      }
    }

    cart.total = cart.items.reduce((acc, cur) => acc + cur.sum, 0);
    this.setData({ cart });
  },

  openDetail() {
    this.setData({ dialogStatus: !this.data.dialogStatus });
  },

  delItem(e) {
    let index = e.currentTarget.dataset.index;
    let cart = this.data.cart;
    cart.items.splice(index, 1);
    cart.total = cart.items.reduce((acc, cur) => acc + cur.sum, 0);
    this.setData({ cart });
  },

  toOrder() {
    if (this.data.cart.items.length === 0) {
      wx.showToast({ title: '购物车为空', icon: 'none' });
      return;
    }
    let order = {
      userId: this.data.cart.userId,
      items: this.data.cart.items,
      total: this.data.cart.total,
      time: new Date().toLocaleString()
    };
    let orderList = wx.getStorageSync('orderList') || [];
    orderList.push(order);
    wx.setStorageSync('orderList', orderList);
    this.setData({ 
      cart: { userId: this.data.cart.userId, items: [], total: 0 } 
    });
    wx.showToast({
       title: '下单成功', 
       icon: 'success' 
      });
    wx.navigateTo({ url: '/pages/order/order' });
  }
});
